package com.todo.demo.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.todo.demo.Model.KeyAndValue;
import com.todo.demo.Model.KeyAndValueTodo;
import com.todo.demo.Model.Result;
import com.todo.demo.Service.LoginService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util<T> {
    private Util() {
    }

    private static Util single = null;

    //静态工厂方法
    public static Util getInstance() {
        if (single == null) {
            single = new Util();
        }
        return single;
    }

    public Result ResultSuccessful(T resultData) {
        Result result = new Result();

        result.setCode(1);
        result.setMsg("成功");
        result.setData(resultData);

        return result;
    }

    public Result ResultFail(String msg) {
        Result result = new Result();

        result.setCode(-1);
        result.setMsg(msg);
        return result;
    }

    public Result ResultUserNotFound(String msg) {
        Result result = new Result();

        result.setCode(-401);
        result.setMsg(msg);
        return result;
    }


    public String getToken(LoginService userService) {
        /**
         *  会进入这里就说明token过期了
         *  在去重新获取
         */

        String appID = "wx5d6db64a11aeb2de";
        String appSecret = "ee51ab838de63f97460b5467d3342656";

        String requestByWx = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", "appid=" + appID + "&secret=" + appSecret + "&grant_type=client_credential");
        JSONObject jsonObject = (JSONObject) JSON.parse(requestByWx);
        String access_token = jsonObject.getString("access_token");


        if (userService.getAccessToken() == null) {
            KeyAndValue keyAndValue = new KeyAndValue();
            keyAndValue.setKey("access_token");
            keyAndValue.setValue(access_token);

            userService.addToken(keyAndValue);
        } else {
            KeyAndValueTodo keyAndValue = new KeyAndValueTodo();
            keyAndValue.setTodo_key("access_token");
            keyAndValue.setTodo_value(access_token);

            userService.updateAccessToken(keyAndValue);
        }
        return access_token;
    }


    public String post(String strURL, String params) {
        System.out.println(strURL);
        System.out.println(params);
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();

            //如果一定要使用如下方式接收响应数据， 则响应必须为: response.getWriter().print(StringUtils.join("{\"errCode\":\"1\",\"errMsg\":\"", message, "\"}")); 来返回
//            int length = (int) connection.getContentLength();// 获取长度
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8"); // utf-8编码
//                System.out.println(result);
//                return result;
//            }

            return res;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }


    /**
     * 使用Calendar对象计算时间差，可以按照需求定制自己的计算逻辑
     *
     * @param strDate
     * @throws ParseException
     */
    public int calculateTimeDifferenceByCalendar(String strDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = formatter.parse(strDate);

        Calendar c1 = Calendar.getInstance();   //当前日期
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date);   //设置为另一个时间

        int year = c1.get(Calendar.DAY_OF_MONTH);
        int oldYear = c2.get(Calendar.DAY_OF_MONTH);

        //这里只是简单的对两个年份数字进行相减，而没有考虑月份的情况

        return year - oldYear;
    }
}